import axios from 'axios'
import router from '../router'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { useMessage } from '@/hooks'
import { LoginKeyEnum } from '@/enums'
import { localCache } from '@/utils/storageCache'

const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.MODE != 'production' ? import.meta.env.VITE_APP_BASE_API : import.meta.env.VITE_APP_SERVER_URL,
  timeout: 10000,
  withCredentials: true
})

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = getToken()
  if(token) {
    config.headers[LoginKeyEnum.HEADER_AUTHORIZATION] = token
  }
  return config
}, (error: any) => {
  console.error(error)
})

instance.interceptors.response.use((response: AxiosResponse) => {
  return response
}, (error: any) => {
  if (error.response) {
    if (error.response.status === 401) {
      useMessage().warning('登录超时，请重新登录')
      router.replace('/login')
    } else if (error.response.status === 402 || error.response.status === 403) {
      useMessage().warning('登录超时，请重新登录')
      router.replace('/login')
    } else if (error.response.status === 404) {
      useMessage().warning('路径找不到~~~')
    }
  } else {
    if (!window.navigator.onLine) {
      useMessage().warning('请检查当前网络设置')
      // 断网处理
      // 跳转到断网页面
    }
    return Promise.reject(error)
  }
})

export function getToken() {
  return localCache.getCache(LoginKeyEnum.SET_TOKEN_KEY)
}

export default instance